package com.kfm.spring.controller;

import com.kfm.spring.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@Controller
@SessionAttributes(value={"user"})
public class ValController {

    private ObjectError allError;

    @RequestMapping("/val")
    public void val(@Valid User user, BindingResult br, Errors errors) throws IOException {
        if(br.hasErrors()){
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                System.out.println(allError.getDefaultMessage());
            }
        }else {
            System.out.println("success");
        }
        System.out.println(user);
    }

    @RequestMapping("/val2")
    public void val2(@Validated(User.Add.class) User user, BindingResult br, Errors errors) {
        if(br.hasErrors()){
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                System.out.println(allError.getDefaultMessage());
            }
        }else {
            System.out.println("success");
        }
        System.out.println(user);
    }

    @RequestMapping("/val3")
    public void val3(@Validated(User.Update.class) User user, BindingResult br, Errors errors) {
        if(br.hasErrors()){
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                System.out.println(allError.getDefaultMessage());
            }
        }else {
            System.out.println("success");
        }
        System.out.println(user);
    }

    @RequestMapping("/val4")
    public String header(@RequestHeader("content-type") String contentType
    , @CookieValue("JSESSIONID") String sessionId, ModelMap modelMap, HttpSession session){
        System.out.println(sessionId);
        System.out.println(contentType);
        System.out.println(modelMap.getAttribute("user"));
        return "hello";
    }
}
